import './../css/common.scss';
import { Component , PropTypes} from "react";

import IScroll from 'iscroll/build/iscroll-probe' ;

export default class PaginationComponent extends Component {
    constructor(){
        super()
        this.onEndReachedThreshold = 40 ;
        this.el = this.refs.el;
        this.timeOut = []
        this.state = {
            flag : false ,
        }
    }
    static childContextTypes  = {
        Pagination : PropTypes.object
    }
    getChildContext() {
        return {
            Pagination : this.Pagination
        };
    }
    static defaultProp = {
        currentPage : 1 ,
        onrefresh:{
            type : Function ,
            default :() => {}
        },
        onloadMore:{
            type:Function,
            default:()=>{}
        },
        scrollFn:{
            type:Function , 
            default:() =>{}
        }
        // PaginationParams : ''
    }
    componentDidMount(){
        let { PaginationElement } = this.refs ;
        this.Pagination = new IScroll('.PaginationContent',{
            mouseWheel: true,
            probeType: 3,  // 调节在scroll事件触发中探针的活跃度或者频率
            scrollbars: "custom",
            fadeScrollbars: true,
            disablePointer: true,
            disableTouch: false,
            disableMouse: false,
            momentum: true,
            click: true//this._iScrollClick()
        })
        this.bindScrollEvent()
        console.log(this.props)
        this.props.scrollFn(this.Pagination)
        //监听窗口变化，刷新iscorll
        document.addEventListener(`touchmove`,this._touchmove,false);
        window.addEventListener(`resize`,this._refresh,false);
    }
    componentWillUnmount(){
        this.Pagination.destroy();
        this.timeOut.forEach(t=>clearTimeout(t));
        document.removeEventListener(`touchmove`,this._touchmove,false);
        window.removeEventListener(`resize`,this._refresh,false);
    }
    bindScrollEvent() {
        let _this = this ;
        this.Pagination.on(`beforeScrollStart`,()=>{
            const diff = _this.getDiff();
            if (diff !== false) {
                _this.cacheY = diff;
                _this.shouldRefresh();
            };
        });

        this.Pagination.on(`scroll`,this.scrollEvent.bind(this));

        this.Pagination.on(`scrollEnd`, this.scrollEvent.bind(this));

    }
    getDiff(){
        let { 
            y ,
            maxScrollY 
        } = this.Pagination ;
        if (y > 0 || Math.abs(y) > Math.abs(maxScrollY)) return false;
        return Math.abs(maxScrollY) - Math.abs(y);
    }
    scrollEvent(){
        this.shouldRefresh();
        const diff = this.getDiff();
        if (diff === false) return;
        if ( Math.abs(diff - this.cacheY) >= 2) {

            let direction = diff - this.cacheY > 0 ? 'down' : 'up';
            if (direction === 'up' && diff < this.onEndReachedThreshold) {
                this.onloadMore();
                this.setState({
                    flag : true 
                })
            } 
            this.cacheY = diff;
        }
    }
    onloadMore(){
        this.props.onloadMore() ;
    }
    shouldRefresh(){
        const {
            scroller,
            wrapperHeight,
            scrollerHeight
        } = this.Pagination;

        const { clientHeight } = scroller;

        let refresh = false;

        if (this.el && this.el.clientHeight !== wrapperHeight) {
            refresh = true;
        }

        if (clientHeight !== scrollerHeight || refresh) {
            this._refresh();
        }
    }
    _touchmove (e) {
        e.preventDefault();
    }
    _refresh() {
        this.Pagination && this.timeOut.push(
            setTimeout(() => this.Pagination.refresh(), 10)
        );
    }
    render(){
        let show = '' ;
        let { flag } = this.state ;
        if(flag){
            show =  <div className="loadMore">加载中...</div> 
        }
        return (
                <div className="PaginationContent" ref="el">
                    <div>
                        {this.props.children}
                        {show}
                    </div> 
                </div> 
        )
    }
}